package com.lyh.seckill.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyh.seckill.pojo.Order;
import com.lyh.seckill.pojo.SeckillMessage;
import com.lyh.seckill.pojo.SeckillOrder;
import com.lyh.seckill.pojo.User;
import com.lyh.seckill.rabbitmq.MQSender;
import com.lyh.seckill.service.IGoodsService;
import com.lyh.seckill.service.IOrderService;
import com.lyh.seckill.service.ISeckillOrderService;
import com.lyh.seckill.utils.JsonUtil;
import com.lyh.seckill.vo.GoodsVo;
import com.lyh.seckill.vo.RespBean;
import com.lyh.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/seckill")
public class SecKillController implements InitializingBean {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    @Autowired
    @Resource
    private RedisScript<Long> script;

    private Map<Long,Boolean> EmptyStockMap = new HashMap<>();


    @RequestMapping("/doSeckill2")
    // model数据对象传入
    public String doSeckill2(Model model, User user, Long goodsId){
        if(user==null){
//           return RespBean.error(RespBeanEnum.LOGIN_ERROR);
           return "login";
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order" + user.getId() + ":" + goodsId);
        if(seckillOrder!=null){
            model.addAttribute("errmsg", RespBeanEnum.REPEATE_ERROR.getMessage());
//            return  RespBean.error(RespBeanEnum.REPEATE_ERROR);
            return "secKillFail";
        }
        //通过内存标记减少redis访问
        if(EmptyStockMap.get(goodsId)){
//           return RespBean.error(RespBeanEnum.EMPTY_STOCK);
            return "secKillFail";
        }
        //预减库存
        //调用一次自动递减  原子性的
        //获取 stock 递减之后的库存 预减库存
//        Long stock = valueOperations.decrement("seckillGoods" + goodsId);
        //通过执行lua脚本获取redis库存
        Long stock = ((Long) redisTemplate.execute(script, Collections.singletonList("seckillGoods:" + goodsId), Collections.EMPTY_LIST));
        if(stock<0){
            EmptyStockMap.put(goodsId,true);
            valueOperations.increment("seckillGoods" + goodsId);
//            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
            return "secKillFail";
        }
        SeckillMessage seckillMessage = new SeckillMessage(user,goodsId);
        mqSender.sendSeckillMessage(JsonUtil.object2JsonStr(seckillMessage));
        //发送消息 通知准备下单 需要准备用户和商品
        //接收到0 展示排队中 页面
//        Order order = orderService.seckill(user,goods);
//        model.addAttribute("order",order);
//        model.addAttribute("goods",goods);
        return "orderDetail";
//        return RespBean.success(0);


//        model.addAttribute("user",user);
//        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
//        //判断库存
//        if(goods.getStockCount()<1){
//            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
//            return "secKillFail";
//        }


        //判断是否重复抢购
//        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id",user.getId()).eq("goods_id",goodsId));

//        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order" + user.getId() + ":" + goodsId);
//        if(seckillOrder!=null){
//            model.addAttribute("errmsg", RespBeanEnum.REPEATE_ERROR.getMessage());
//            return "secKillFail";
//        }
//        Order order = orderService.seckill(user,goods);
//        model.addAttribute("order",order);
//        model.addAttribute("goods",goods);
//        return "orderDetail";

//        return null;
    }


    //获取秒杀结果
    //orderId:成功 -1:失败 0:排队中
    @RequestMapping(value = "/result",method = RequestMethod.GET)
    @ResponseBody
    public RespBean getResult(User user,Long goodsId) {
        if(user==null){
            return  RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        Long orderId = seckillOrderService.getResult(user,goodsId);
        return RespBean.success(orderId);
    }


    @RequestMapping("/doSeckill")
    // model数据对象传入
    public String doSeckill(Model model, User user,Long goodsId){
        if(user==null){
            return "login";
        }
        model.addAttribute("user",user);
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
        //判断库存
        if(goods.getStockCount()<1){
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return "secKillFail";
        }
        //判断是否重复抢购
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id",user.getId()).eq("goods_id",goodsId));
        if(seckillOrder!=null){
            model.addAttribute("errmsg", RespBeanEnum.REPEATE_ERROR.getMessage());
            return "secKillFail";
        }
        Order order = orderService.seckill(user,goods);
        model.addAttribute("order",order);
        model.addAttribute("goods",goods);
        return "orderDetail";
    }


    //系统初始化 把商品数量加载到redis库存里面去
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> list = goodsService.findGoodsVo();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        //商品号与库存以map形式绑定存入redis
        list.forEach(goodsVo ->
                {redisTemplate.opsForValue().set("seckillGoods"+goodsVo.getId(),
                        goodsVo.getStockCount());
                    EmptyStockMap.put(goodsVo.getId(),false);
                }
        );
    }
}
